package br.com.upcoder.fguard.client;

import br.com.upcoder.fguard.client.presenter.AddDebtPresenter;
import br.com.upcoder.fguard.client.presenter.ListBudgetsPresenter;
import br.com.upcoder.fguard.client.presenter.Presenter;
import br.com.upcoder.fguard.client.presenter.event.AddDebtEvent;
import br.com.upcoder.fguard.client.presenter.event.AddDebtEventHandler;
import br.com.upcoder.fguard.client.shared.Budget;
import br.com.upcoder.fguard.client.view.AddDebtView;
import br.com.upcoder.fguard.client.view.ListBudgetsView;

import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.ui.HasWidgets;

public class AppController implements ValueChangeHandler<String> {

	private HandlerManager eventBus;
	private HasWidgets container;

	public AppController(HandlerManager eventBus) {
		this.eventBus = eventBus;
		bind();
	}

	private void bind() {
		// Registrando listener para qualquer transicao efetuada no historico
		History.addValueChangeHandler(this);

		eventBus.addHandler(AddDebtEvent.TYPE, new AddDebtEventHandler() {
			@Override
			public void onAddDebt(AddDebtEvent event) {
				doAddDebt(event.getBudget());
			}
		});
	}

	protected void doAddDebt(Budget budget) {
		History.newItem("addDebt", false);
		new AddDebtPresenter(eventBus, new AddDebtView(), budget).go(container);
	}

	public void go(HasWidgets container) {
		this.container = container;
		if ("".equals(History.getToken())) {
			History.newItem("list");
		} else {
			History.fireCurrentHistoryState();
		}
	}

	@Override
	public void onValueChange(ValueChangeEvent<String> event) {
		String token = event.getValue();
		if (token != null) {
			Presenter presenter = null;
			if ("list".equals(token)) {
				presenter = new ListBudgetsPresenter(eventBus,
						new ListBudgetsView());
			}
			if ("addDebt".equals(token)) {
				presenter = new AddDebtPresenter(eventBus, new AddDebtView());
			}

			if (presenter != null) {
				presenter.go(container);
			}
		}
	}
}
